<!-- 组件html内容 -->
<template>
  <!-- 一定要有一个根标签div class属性值是组件名称 -->
  <div class="AddEditShow">
    <el-form :disabled="formState==3?true:false" :rules="addEditShowrules" ref="addEditShowForm"
      :model="addEditShowFormData" label-width="130px">
      <el-divider content-position="left">账号信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input placeholder="请设置用户名" maxlength="10" v-model="addEditShowFormData.userName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formState==1">
          <el-form-item label="密码" prop="userAuthString">
            <el-input placeholder="请设置密码" maxlength="10" v-model="addEditShowFormData.userAuthString"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">实名信息</el-divider>
      <el-row>

        <el-col :span="12">
          <el-form-item label="真实姓名">
            <el-input placeholder="请输入真实姓名" maxlength="15" v-model="addEditShowFormData.realName"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="身份证号码">
            <el-input placeholder="请输入身份证号码" maxlength="25" v-model="addEditShowFormData.idCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>

        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="addEditShowFormData.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生日">
            <el-date-picker style="width: 100%;" placeholder="请选择您的生日" v-model="addEditShowFormData.birthDate"
              type="date">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input placeholder="请输入邮箱" maxlength="30" v-model="addEditShowFormData.userEmail"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码">
            <el-input placeholder="请输入手机号码" maxlength="30" v-model="addEditShowFormData.telNumber"></el-input>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row v-if="formState!=1">
        <el-col :span="12">
          <el-form-item label="用户状态">
            <el-switch v-model="addEditShowFormData.userState" active-color="#13ce66" inactive-color="#ff4949"
              :active-value="1" :inactive-value="2" active-text="正常" inactive-text="锁定">
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formState==3">
          <el-form-item label="最后一次登录时间">
            <el-input v-model="addEditShowFormData.lastLoginTime"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12" v-if="formState==3">
          <el-form-item label="登录错误次数">
            <el-input v-model="addEditShowFormData.errCount"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formState==3">
          <el-form-item label="最后登录的ip" v-if="formState!=1">
            <el-input v-model="addEditShowFormData.lastLoginIP"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">用户头像</el-divider>
      <el-row>
        <el-upload class="avatar-uploader" action="/ynnz_ssm/file/upload?busDesc='用户头像'" :show-file-list="false"
          :on-success="handleUserPhotoSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="addEditShowFormData.photoFileID!=null" :src="'/ynnz_ssm/file/fileDownLoad?fileID='+addEditShowFormData.photoFileID" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-row>

      <el-form-item v-if="formState==3?false:true">
        <el-button @click="reset('addEditShowForm')" v-if="formState==1">重置</el-button>
        <el-button type="primary" @click="save">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<!-- 组件js部分 -->
<script>
  export default {
    name: 'AddEditShow', //组件的名称-要和文件名相同（驼峰规则命名）
    props: {
      // 接收表单回填的数据对象
      editOrShowData: {
        userID: null // 提供编辑前去查询数据库，查看详情时查询数据库
      },
      // 操作状态  1 添加 2 编辑 3 查看
      formState: 1
    },
    data() {
      return {
        // 表单数据
        addEditShowFormData: {
          userID: null,
          userName: null,
          userAuthString: null,
          userEmail: null,
          realName: null,
          birthDate: null,
          sex: 1,
          telNumber: null,
          idCode: null,
          errCount: 0,
          userState: 1,
          lastLoginTime: null,
          lastLoginIP: null,
          photoFileID: null,
          photoBase64: null
        },
        // 添加编辑表单验证
        addEditShowrules: {
          userName: [{
              required: true,
              message: '请设置用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          userAuthString: [{
              required: true,
              message: '请设置密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          sex: [{
            required: true,
            message: '请选择性别',
            trigger: 'change'
          }]
        }
      }
    },
    mounted() {
      if (this.formState != 1) { // 编辑、详情
        let _this = this;
        this.$axios.get('/user/getUserByID', {
            params: {
              // GET请求参数
              userID: _this.editOrShowData.userID,
            }
          }) // http://localhost:25100/api/user/getUserByID/101
          .then(function(res) { // 请求成功 HTTP状态码是200
            _this.addEditShowFormData = res.data.data;

          })
          .catch(function(error) { // 请求失败处理
            console.log(error);
          });
      }
    },
    methods: {
      // 提交
      save() {

        this.$refs.addEditShowForm.validate((valid) => {
          if (valid) {
            if (this.formState == 1) { // 添加

              let _this = this;
              this.$axios.post('/user/addUser', this.addEditShowFormData)
                .then(function(res) { // 请求成功 HTTP状态码是200
                  // res参数：封装了请求响应、请求参数、请求配置等等信息
                  // 后端响应数据：res.data
                  console.dir(res.data);
                  if (res.data.code == 200) {
                    _this.$message.success(res.data.msg);
                    _this.$emit("needClose", _this.formState)
                  } else {
                    _this.$message.error(res.data.msg);
                  }
                })
                .catch(function(error) { // 请求失败处理
                  console.log(error);
                });
            } else { // 编辑

              let _this = this;
              this.$axios.put('/user/updateUser', this.addEditShowFormData)
                .then(function(res) { // 请求成功 HTTP状态码是200
                  // res参数：封装了请求响应、请求参数、请求配置等等信息
                  // 后端响应数据：res.data
                  console.dir(res.data);
                  if (res.data.code == 200) {
                    _this.$message.success(res.data.msg);
                    // 告诉父组件弹窗要关闭
                    _this.$emit("needClose", _this.formState)
                  } else {
                    _this.$message.error(res.data.msg);
                  }
                })
                .catch(function(error) { // 请求失败处理
                  console.log(error);
                });

            }

          } else {
            return false;
          }
        });



      },
      // 重置表单（仅在添加时使用）
      reset(formRel) {
        this.$refs[formRel].resetFields();
      },
      // 当用户头像上传成功
      handleUserPhotoSuccess(res, file) {
        console.dir(res);
        if (res.code == 200) {
          this.$message.success(res.msg);
          // 1.上传图片成功后将获取的base64赋给图片显示字段
          this.addEditShowFormData.photoBase64 = 'data:image/gif;base64,' + res.data.base64Img;
          this.addEditShowFormData.photoFileID = res.data.fileID;
        } else {
          this.$message.error(res.msg);
        }

      },
      // 头像上传前拦截类型和大小
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    },
    watch: {

    }
  }
</script>

<!-- 3.组件的css样式部分 scoped：当前声明的样式只提供给当前组件使用 -->
<style scoped>
  /deep/ .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  /deep/.el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
